//
//  AUAccountManager.swift
//  AwesomeUBaseModule
//
//  Created by Miss_Special on 2018/5/9.
//

// MARK: - Static value
let kAUAccountManager_CacheKey_Account = "kAUAccountManager_CacheKey_Account"

// MARK: - Manager
public class AUAccountManager: AUProtocol_Cache {
    
    public static let sharedInstance = AUAccountManager()
    
    private init() {
        if accountModel == nil {
            accountModel = cache_unarchive(forKey: kAUAccountManager_CacheKey_Account) as? AUAccountModel
            print("userID: \(accountModel?.userID ?? "")")
        }
    }
    
    /// accountModel
    private (set) public var accountModel: AUAccountModel? {
        didSet {
            guard let model = accountModel else {
                return
            }
            model.cache_archive(forKey: kAUAccountManager_CacheKey_Account)
        }
    }
    
    /// loginStatus
    public var isLogin: Bool {
        return accountModel == nil ? false : true
    }
    
    /// updateAccount
    public func updateAccount(dict: [String: Any]) {
        accountModel = AUAccountModel(dict: dict)
    }
    
    /// removeAccount
    public func removeAccount() {
        cache_remove_archive()
        accountModel = nil
    }
}

// MARK: - Model
public class AUAccountModel: NSObject, NSCoding, AUProtocol_Cache {
    
    // MARK: Params
    @objc private (set) public var userID: String?
    @objc private (set) public var token: String?
    
    // MARK: System
    init(dict: [String: Any]) {
        super.init()
        
        setValuesForKeys(dict)
    }
    
    override public func setValue(_ value: Any?, forUndefinedKey key: String) { }
    
    // MARK: NSCoding
    public func encode(with aCoder: NSCoder) {
        aCoder.encode(userID, forKey: "au_userID")
        aCoder.encode(token, forKey: "au_token")
    }
    
    required public init?(coder aDecoder: NSCoder) {
        userID = aDecoder.decodeObject(forKey: "au_userID") as? String
        token = aDecoder.decodeObject(forKey: "au_token") as? String
    }
}
